/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;


import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.*;
import model.pojo.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Mr.Thanh
 */
public class administrator extends HttpServlet {

    
    String page = "";
    String action="";
    HttpSession session; 
     QuanTriPOJO quantri=null;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        page = request.getParameter("page");
        action=request.getParameter("action");
        session = request.getSession(); 
               
        try {
            if(action!=null){               
                
                if(action.equals("view")||action.equals("struct")){  
                                 
                    ViewStruct(request, response);
                    
                }else if(action.equals("edit")||action.equals("insert")||action.equals("delete")){  
                        
                     InsertUpdateDelete(request, response);
                    
                }else if(action.equals("login")){
                    LoginLogout(request, response);
                    
                }else if(action.equals("logout")){  
                    synchronized (session){
                                    session.removeAttribute("Admin");
                        }  
                    response.sendRedirect("administrator.html?page=login&action=view");
                }
                
            }else {
                response.sendRedirect("administrator.html?page=home&action=view");
            }
        } finally {  
            out.flush();
            out.close();
        }
    }
    
    
    private void LoginLogout(HttpServletRequest request, HttpServletResponse response){
        try{
                String tendangnhap="";
                if(request.getParameter("txtTenDangNhap")!=null){
                    tendangnhap=request.getParameter("txtTenDangNhap");
                }
                String matkhau="";
                if(request.getParameter("txtMatKhau")!=null){
                    matkhau=request.getParameter("txtMatKhau");
                }


                quantri=QuanTriDAO.login(tendangnhap,matkhau);
                if(quantri!=null){  
                    //kiem tra xem cho nho mat khau cho lan dang nhap sau ko
                    //neu co thi luu: ten dang nhap, mat khau
                    if(request.getParameterValues("chkNhoDangNhap")!=null && request.getParameterValues("chkNhoDangNhap").length==1)
                    {
                        synchronized (session){
                                session.setAttribute("TenDangNhap",tendangnhap);
                                session.setAttribute("MatKhau",matkhau);
                        }  
                    }else{ //khong co thi xoa :ten dang nhap, mat khau
                        session.removeAttribute("TenDangNhap");
                        session.removeAttribute("MatKhau");
                    }
                    //luu thong tin nguoi dang nhap
                    synchronized (session){
                                session.setAttribute("Admin",quantri);
                    }  
                    response.sendRedirect("administrator.html?page=home&action=view");
                }else{
                    request.getRequestDispatcher("/administrator/login.jsp").forward(request, response);
                }   
        }catch(Exception e){}
        
    }
    
    
    
    private void ViewStruct(HttpServletRequest request, HttpServletResponse response){
        try{
            int trang=1;
            if(page!=null){
                int soTrang=1;
                if(request.getParameter("p")!=null){
                    trang=Integer.parseInt(request.getParameter("p"));
                }

                if(session.getAttribute("Admin")!=null && !page.equals("home")){   

                        soTrang=PhanTrangDAO.tinhSoLuongTrang(page.trim());                                    
                        request.setAttribute("trang",trang);
                        request.setAttribute("soTrang", soTrang);
                        if(action.equals("view")){
                            HashMap<Vector,ArrayList<adminTableColumnsPOJO>> ds=administratorDAO.getTablePage("vndoan", page.trim(),trang);
                            request.setAttribute("DanhSach", ds);
                            request.getRequestDispatcher("/administrator/view.jsp").include(request, response);                                        


                        }else if(action.equals("struct")){
                            HashMap<Vector,ArrayList<String>> ds=administratorDAO.getTableStruct("vndoan", page.trim());
                            request.setAttribute("DanhSach", ds);
                            request.getRequestDispatcher("/administrator/struct.jsp").include(request, response);
                        }



                }else if(page.equals("login")){ //hien thi trang login   
                    if(session.getAttribute("AutoLogin")!=null){//tu dong login neu chon nho mat khau luc login
                        HashMap<Vector,ArrayList<String>> ds=administratorDAO.getAllTableInfo("vndoan");
                        request.setAttribute("DanhSach", ds);
                        request.getRequestDispatcher("/administrator/home.jsp").forward(request, response);
                    }else{
                        request.getRequestDispatcher("/administrator/login.jsp").forward(request, response);
                    }
                }else{//kiem tra xem login chua
                    if(session.getAttribute("Admin")!=null){
                        HashMap<Vector,ArrayList<String>> ds=administratorDAO.getAllTableInfo("vndoan");
                        request.setAttribute("DanhSach", ds);
                        request.getRequestDispatcher("/administrator/home.jsp").forward(request, response);
                    }else{
                        response.sendRedirect("administrator.html?page=login&action=view");
                    }

                }
            }else{
                request.getRequestDispatcher("/administrator/login.jsp").forward(request, response);
           }          
        }catch(Exception e){}
        
    }
    
    
    
     private void InsertUpdateDelete(HttpServletRequest request, HttpServletResponse response){
        try{
           if(page!=null){
                          
                if(session.getAttribute("Admin")!=null){   
                    Vector All=new Vector();
                    HashMap<Vector,ArrayList<String>>  ds;
                    if(action.equals("edit")){

                            //edit 1 dong
                            String apply=request.getParameter("apply");
                            if(apply==null){
                                    String KeyColumnName=request.getParameter("KeyColumnName").trim();
                                    if(request.getParameter("id")!=null){
                                        ds=administratorDAO.getTableUpdateDelete( page.trim(),KeyColumnName,request.getParameter("id").trim());
                                         All.add(ds);
                                    }else{
                                            String[] dsId=request.getParameterValues("Ids[]");

                                            for(String s:dsId){
                                                ds=administratorDAO.getTableUpdateDelete( page.trim(),KeyColumnName,s.trim());
                                                All.add(ds);
                                            }                                           
                                    }
                                     //ajax
                                     request.setAttribute("DanhSach", All);
                                     request.getRequestDispatcher("/administrator/change.jsp").include(request, response);
                            }else{
                                String[] Fields=request.getParameterValues("Field");                              

                                //tao cau truy van hoan chinh
                                String sql=GetUpdteQuery(request,page,Fields);
                                ArrayList<String> resultUpdate=new ArrayList<String>();
                                resultUpdate.add(administratorDAO.insertUpdate(page.trim(), sql));
                                request.setAttribute("Result", resultUpdate);
                                request.getRequestDispatcher("/administrator/success.jsp").forward(request, response);
                                UploadFile(request, response);
                            }


                    }else if(action.equals("delete")){
                                String KeyColumnName=request.getParameter("KeyColumnName").trim();
                                //edit 1 dong
                                ArrayList<String> resultDelete=new ArrayList<String>();
                                if(request.getParameter("id")!=null){                                              
                                     resultDelete.add(administratorDAO.deleteRowById( page.trim(),KeyColumnName,request.getParameter("id").trim()));
                                }else{
                                    String[] dsId=request.getParameterValues("Ids[]");

                                    for(String s:dsId){
                                        resultDelete.add(administratorDAO.deleteRowById(page.trim(),KeyColumnName,s.trim()));
                                    }
                                }
                                request.setAttribute("Result", resultDelete);
                                 //ajax
                                 request.setAttribute("DanhSach", All);
                                 request.getRequestDispatcher("/administrator/change.jsp").include(request, response);

                   }else if(action.equals("insert")){

                         String apply=request.getParameter("apply");
                          if(apply==null){
                                 ds=administratorDAO.getTableAdd( page.trim());
                                 All.add(ds);
                                 //ajax
                                 request.setAttribute("DanhSach", All);
                                 request.getRequestDispatcher("/administrator/change.jsp").include(request, response);
                          }else{
                                String[] Fields=request.getParameterValues("Field");                             

                                //tao cau truy van hoan chinh
                                String sql=GetInsertQuery(request,page,Fields);
                                ArrayList<String> resultUpdate=new ArrayList<String>();
                                resultUpdate.add(administratorDAO.insertUpdate(page.trim(), sql));
                                request.setAttribute("Result", resultUpdate);
                                request.getRequestDispatcher("/administrator/success.jsp").forward(request, response);
                                 UploadFile(request, response);
                            }

                    }else if(action.equals("delete")){
                            ArrayList<String> resultDelete=new ArrayList<String>();
                            String KeyColumnName=request.getParameter("KeyColumnName").trim();
                            //edit 1 dong
                            if(request.getParameter("id")!=null){
                               resultDelete.add(administratorDAO.deleteRowById(page.trim(),KeyColumnName,request.getParameter("id").trim()));
                             }
                            //ajax
                            request.setAttribute("Result", resultDelete);
                            request.setAttribute("DanhSach", All);
                            request.getRequestDispatcher("/administrator/change.jsp").include(request, response);

                    }
                    


                }else if(page.equals("login")){ //hien thi trang login   
                    if(session.getAttribute("AutoLogin")!=null){//tu dong login neu chon nho mat khau luc login
                        HashMap<Vector,ArrayList<String>> ds=administratorDAO.getAllTableInfo("vndoan");
                        request.setAttribute("DanhSach", ds);
                        request.getRequestDispatcher("/administrator/home.jsp").forward(request, response);
                    }else{
                        request.getRequestDispatcher("/administrator/login.jsp").forward(request, response);
                    }
                }else{//kiem tra xem login chua
                    if(session.getAttribute("Admin")!=null){
                        HashMap<Vector,ArrayList<String>> ds=administratorDAO.getAllTableInfo("vndoan");
                        request.setAttribute("DanhSach", ds);
                        request.getRequestDispatcher("/administrator/home.jsp").forward(request, response);
                    }else{
                        response.sendRedirect("administrator.html?page=login&action=view");
                    }

                }
            }else{
                request.getRequestDispatcher("/administrator/login.jsp").forward(request, response);
           }                   
                    
        }catch(Exception e){}
        
    }
    
      
    private String GetUpdteQuery(HttpServletRequest request,String page,String[] Fields){
//        boolean isMultiPart=ServletFileUpload.isMultipartContent(request);
//        if(isMultiPart){
//           FileItemFactory factory=new DiskFileItemFactory(); 
//           ServletFileUpload upload=new ServletFileUpload(factory);
//           Vector items=new Vector();
//           try{
//               items.add(upload.parseRequest(request));              
//           
//           }catch(Exception e){}
//           
//           Iterator iter=items.iterator();
//           Hashtable prams=new Hashtable();
//           String filename=null;
//           while(iter.hasNext()){
//               FileItem item=(FileItem)iter.next();
//               if(item.isFormField()){
//                   prams.put(item.getFieldName(), item.getString());
//               }else{
//                   try{
//                       String itemName=item.getName();
//                       filename=itemName.substring(itemName.lastIndexOf("\\")+1);
//                       String RealPath=getServletContext().getRealPath("/")+"HinhAnh\\"+filename;
//                       File saveFile=new File(RealPath);
//                       item.write(saveFile);
//                   }catch(Exception e){
//                   }
//               }
//           }
//        }
        
        String update=String.format("UPDATE `%s` ",page.trim());
        String set="SET ";
        String where="WHERE ";
        
        for(String field:Fields){
           boolean isKey=false;
           String[] value=request.getParameterValues(field);                                               
           if(value.length<1){
               continue;
           }
           String type=field.substring(field.lastIndexOf("_")+1).trim();
           //loai bo type ra 
           field=field.substring(0,field.lastIndexOf("_"));
           //kiem tra column co phai la khoa chinh khong,neu co thi se dua vao menh de where
           if(field.endsWith("PRI")){
               //lay ten column
               field=field.substring(0,field.indexOf("_"));
               String temp=String.format(" `%s`.`%s`='%s' AND",page.trim(),field,value[0].toString().trim());
               where+=temp;
               isKey=true;
            }else{
               //lay ten column
               field=field.substring(0,field.indexOf("_"));
               //kiem tra type cua column co fai la bit ko neu co thi fai them b truoc gia tri can set
               //b: chuyen sang dang bit
               String b="";             
              
               if(type.equals("bit")){
                   b="b";                   
               }
               
               //neu gia tri la rong thi se gan gia tri NULL
               String tempValue=value[0].toString().trim();
               if(tempValue.equals("")&&!type.equals("bit")){
                   tempValue="NULL";
                   b="";
               }else if(tempValue.equals("")&&type.equals("bit")){
                   tempValue="0";
               }
               //qui dinh cau truc md5 la:  MD5:giatri
               if(tempValue.trim().startsWith("MD5:")){                   
                     tempValue=tempValue.substring(4);                    
                     b="";
                     tempValue=String.format("MD5('%s')", tempValue);
               }else{
                   //kiem tra truog hop khong nhap khoa chinh,de tu dong
                   //thi qui dinh fai la -1
                   //nen ta fai kiem tra xem gia tri khoa co tu dong ko
                   //neu tu dong thi se gan gia tri NULL
                   if(isKey==true){  
                       int id=-1;
                       try{
                           id=Integer.parseInt(tempValue);
                           if(id<0){
                               tempValue="NULL";
                           }else{
                               tempValue=String.format("'%s'", tempValue);
                           }
                       }catch(Exception e){                           
                       }
                   }else{
                       tempValue=String.format("'%s'", tempValue);
                   }
                   
               }
               String temp=String.format(" `%s`.`%s`=%s%s ,",page.trim(),field,b,tempValue.trim());
               set+=temp;
           }                                   


        }                                  

         //kiem tra xem set co du dau phay cuoi ko
        if(set.endsWith(",")){
            set=set.substring(0,set.length()-1);
        }

         //kiem tra xem where co du and cuoi ko
        if(where.lastIndexOf("AND")>0){
            where=where.trim().substring(0,where.length()-4);
        }
        return String.format("%s %s %s", update,set,where);
    }
    
        
    private String GetInsertQuery(HttpServletRequest request,String page,String[] Fields){
        String insert=String.format("INSERT INTO `%s` ",page.trim());
        String into="";
        String value="";
        
        for(String field:Fields){
           boolean isKey=false;
           String[] val=request.getParameterValues(field);                                               
           if(val.length<1){
               continue;
           }
           String type=field.substring(field.lastIndexOf("_")+1).trim();
           //loai bo type ra 
           field=field.substring(0,field.lastIndexOf("_"));
           if(field.endsWith("PRI")){
               isKey=true;
           }
           //lay ten column
           String temp="";
           field=field.substring(0,field.indexOf("_"));
           temp=String.format("`%s`,",field);
           into+=temp;
           //kiem tra type cua column co fai la bit ko neu co thi fai them b truoc gia tri can set
           //b: chuyen sang dang bit
           String b="";
           if(type.equals("bit")){
               b="b";
           }
            //neu gia tri la rong thi se gan gia tri NULL
           String tempValue=val[0].toString().trim();
           if(tempValue.equals("")&&!type.equals("bit")){
               tempValue="NULL";
               b="";
           }else if(tempValue.equals("")&&type.equals("bit")){
               tempValue="0";
           }
           //qui dinh cau truc md5 la:  MD5:giatri
           if(tempValue.trim().startsWith("MD5:")){                   
                 tempValue=tempValue.substring(4);                    
                 b="";
                 tempValue=String.format("MD5('%s')", tempValue);
           }else{
               //kiem tra truog hop khong nhap khoa chinh,de tu dong
                   //thi qui dinh fai la -1
                   //nen ta fai kiem tra xem gia tri khoa co tu dong ko
                   //neu tu dong thi se gan gia tri NULL
                   if(isKey==true){  
                       int id=-1;
                       try{
                           id=Integer.parseInt(tempValue);
                           if(id<0){
                               tempValue="NULL";
                           }else{
                               tempValue=String.format("'%s'", tempValue);
                           }
                       }catch(Exception e){                           
                       }
                   }else{
                       tempValue=String.format("'%s'", tempValue);
                   }
           }
           
           temp=String.format(" %s%s ,",b,tempValue.trim());
           value+=temp;
                                          


        }                                  

         //kiem tra xem set co du dau phay cuoi ko
        if(into.endsWith(",")){
            into=into.substring(0,into.length()-1);
        }

         //kiem tra xem where co du and cuoi ko
        if(value.endsWith(",")){
            value=value.substring(0,value.length()-1);
        }
        return String.format("%s (%s) VALUES(%s)", insert,into,value);
    }
    
    
    
    private boolean UploadFile(HttpServletRequest request, HttpServletResponse response){
            //to get the content type information from JSP Request Header
        String contentType = request.getContentType();
        try{
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                DataInputStream in = new DataInputStream(request.getInputStream());
                //we are taking the length of Content type data
                int formDataLength = request.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
                //this loop converting the uploaded file into byte code
                while (totalBytesRead < formDataLength) {
                        byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                        totalBytesRead += byteRead;
                        }
                 String file = new String(dataBytes);
                //for saving the file name
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1,contentType.length());
                int pos;
                //extracting the index of file 
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
                // creating a new file with the same name and writing the content in new file
                FileOutputStream fileOut = new FileOutputStream(saveFile);
                fileOut.write(dataBytes, startPos, (endPos - startPos));
                fileOut.flush();
                fileOut.close();
             }
        }catch(Exception e){}
        
       return true;

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
